<template>
  <KView class="bargain-situation">
    <KView class="bargain-situation-header">
      <page-header title="砍价详情" @back-click="toBack"></page-header>
    </KView>
    <KView v-if="isShow" class="bargain-situation-content">
      <KView class="bargain-situation-time">
        <bargain-countdown-view :bargain="bargainData" @type-change="typeChange"></bargain-countdown-view>
      </KView>
      <KView class="bargain-situation-rect bargain-situation-goods clearfix">
        <KView class="bargain-situation-img">
          <sys-image :src="bargainData.pic" mode="auto" :radius="8"></sys-image>
        </KView>
        <KView class="bargain-situation-info">
          <KView class="bargain-situation-name ellipsis">{{bargainData.name}}</KView>
          <KView class="bargain-situation-data clearfix">
            <KView class="bargain-situation-price">
              <span class="price-unit">¥</span>
              <span class="price-num">{{bargainData.price}}</span>
            </KView>
            <KView class="bargain-situation-soucePrice">¥{{bargainData.sourcePrice}}</KView>
            <KView class="bargain-situation-count">已领{{bargainData.saledCount}}件</KView>
          </KView>
        </KView>
      </KView>
      <KView class="bargain-situation-rect bargain-situation-bargaining">
        <bargain-view :bargain="bargainData" @to-bargain="toBargain" @join-bargain="joinBargain" @pay-momeny="toPayMomeny"></bargain-view>
      </KView>
      <KView class="bargain-situation-rect bargain-situation-record">
        <bargain-record-view :records="bargainData.recordList"></bargain-record-view>
      </KView>
    </KView>
  </KView>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';
  import repeatRequest from 'mixins/repeatRequest';

  import PageHeader from 'common/pageHeader';
  import SysImage from 'common/sysImage';
  import BargainCountdownView from './bargainCountdownView';
  import BargainView from './bargainView';
  import BargainRecordView from './bargainRecordView';

  import GroupBargainApi from 'services/groupBargainApi';

  const vueData = {
    isShow: false,
    isMiniprogram: process.env.isMiniprogram,
    bargainData: null,
    sysUser: null
  };

  import storeMixins from 'mixins/storeMixins';

  export default {
    mixins: [repeatRequest,storeMixins],

    data() {
      let id = this.$route.params.id;
      vueData.id = id;
      let unionid = this.$route.query.unionid;
      if (SystemUtil.isEmpty(unionid)) {
        unionid = null;
      }
      vueData.unionid = unionid;
      return vueData;
    },

    created() {
      if (SystemUtil.isEmpty(this.id)) {
        this.toBack();
        return;
      }

      this.sysUser = this.user;
      let unionid = this.unionid;
      if (unionid !== null && unionid === this.user.unionid) {
        this.unionid = null;
      }

      SystemUtil.showLoading();
      this.setBargainData().then(bargainData => {
        if (bargainData === null) {
          SystemUtil.hideLoading();
          return;
        }
        return this.toInitData().then(() => {
          this.isShow = true;
          SystemUtil.hideLoading();
        });
      }).catch(() => {
        SystemUtil.hideLoading();
      });
    },

    methods: {
      setBargainData() {
        return GroupBargainApi.getGoodsBargainSituation(this.id, this.unionid).then(res => {
          let systemTime = res.systemTime;
          let nowTime = this.$moment().valueOf();
          let rangeTime = 60 * 1000;
          if (!this.$moment(systemTime).isBetween(nowTime - rangeTime, nowTime + rangeTime, 'second', '[]')) {
            SystemUtil.alert('本地时间与服务器时间不同步，请重新设置时间', '提示').then(() => {
              this.toBack();
            }).catch(() => {});
            return null;
          }

          let bargainData = res.data;
          this.bargainData = bargainData;
          return bargainData;
        });
      },

      toInitData(isPrice = false) {
        let bargainData = this.bargainData;
        return this.setRecordList(isPrice).then(() => {
          if (bargainData.type === 1 && bargainData.discountedRate !== 0) {
            this.recordListRunning();
          }
          return bargainData;
        });
      },

      setRecordList(isPrice = true) {
        return GroupBargainApi.getGoodsBargainRecordList(this.bargainData, isPrice).then(data => {
          let bargainData = this.bargainData;
          bargainData.resetData(data);
          return bargainData;
        });
      },

      typeChange(type) {
        this.clearTimeoutList();

        let msg = type === 1 ? '开始砍价' : '结束砍价';
        SystemUtil.showLoading(msg);
        this.toInitData(true).then(() => {
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      toBargain() {
        let bargainData = this.bargainData;
        SystemUtil.showLoading('提交中...');
        GroupBargainApi.bargainGoods(bargainData).then(msg => {
          return this.setRecordList().then(() => {
            bargainData.isBargaining = true;
            SystemUtil.hideLoading();
          });
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      joinBargain() {
        let id = this.id;
        let url = `/bargainSituation/${id}`;
        if (this.isMiniprogram) {
          this.$emit('to-page', url);
        }
      },

      toPayMomeny() {
        SystemUtil.showLoading('');
        GroupBargainApi.toPayBargainGoods(this.bargainData, this.location.lnglat).then(orderId => {
          SystemUtil.hideLoading();
          let url = `/paymentGoods/${orderId}?type=bargain`;
          if (this.isMiniprogram) {
            window.open(url);
          }
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      recordListRunning() {
        this.timeoutList[0] = setTimeout(() => {
          if (this.isDestroy) {
            return;
          }
          this.setRecordList().then(() => {
            if (this.timeoutList[0] === null) {
              return;
            }

            let bargainData = this.bargainData;
            if (bargainData.type !== 1 || bargainData.discountedRate === 0) {
              return;
            }

            this.timeoutList[0] = null;
            this.recordListRunning();
          });
        }, 3000);
      },

      resetBargainData() {
        this.bargainData.isPay = true;
      },

      toBack() {
        let id = this.id;
        let url = `/goodsBargainDetail/${id}`;
        if (this.isMiniprogram) {
          this.$emit('to-page', url);
        }
      }
    },

    components: {
      PageHeader,
      SysImage,
      BargainCountdownView,
      BargainView,
      BargainRecordView
    }
  };

  if (process.env.isMiniprogram) {
    let pathname = window.location.pathname;
    if (pathname.startsWith('/bargainSituation')) {
      window.onShareAppMessage = function (data) {
        let from = data.from;
        let bargainData = vueData.bargainData;
        let defId = bargainData.defId;
        if (from === 'menu') {
          return {
            path: `/bargainSituation/${defId}`
          };
        }

        if (!bargainData.isBargaining) {
          return {
            path: `/bargainSituation/${defId}`
          };
        }

        let unionid = bargainData.unionid;
        if (unionid === null) {
          unionid = vueData.sysUser.unionid;
        }
        let url = `/bargainSituation/${defId}?unionid=${unionid}`;
        return {
          path: url
        }
      }
    }
  }

</script>

<style lang="scss">
  .bargain-situation {
    height: 100%;
    background: #fd5a3a;

    .bargain-situation-header {
      background: #ffffff;
      padding-bottom: formatPx(20);
    }

    .bargain-situation-content {
      padding: formatPx(35) formatPx(30) 0;
      height: calc(100% - #{formatPx(120)});

      .bargain-situation-time {
        text-align: center;

        .bargain-situation-countdown-view {
          display: inline-block;
        }
      }

      .bargain-situation-rect {
        padding: formatPx(30);
        background: #ffffff;
        border-radius: 8px;
      }

      .bargain-situation-goods {
        margin-top: formatPx(25);
        height: formatPx(161);

        >div {
          float: left;
          height: 100%;
        }

        .bargain-situation-img {
          height: calc(100% - 2px);
          width: calc(#{formatPx(161)} - 2px);
          border: 1px solid #F0F0F0;
          border-radius: 8px;
          overflow: hidden;
          margin-right: formatPx(25);
        }

        .bargain-situation-info {
          width: calc(100% - #{formatPx(186)});

          .bargain-situation-name {
            font-size: formatPx(30);
            color: #2f3135;
          }

          .bargain-situation-data {
            color: #b3b9c2;
            margin-top: formatPx(50);

            .bargain-situation-price {
              float: left;
              color: #fd5a3a;
              font-weight: bold;
              text-align: center;

              .price-unit {
                font-size: formatPx(32);
                line-height: formatPx(40);
                margin-right: formatPx(5);
              }

              .price-num {
                font-size: formatPx(40);
                line-height: formatPx(40);
              }
            }

            .bargain-situation-soucePrice {
              float: left;
              font-size: formatPx(30);
              line-height: formatPx(50);
              margin-left: formatPx(15);
              text-decoration: line-through;
            }

            .bargain-situation-count {
              float: right;
              margin-left: formatPx(15);
              font-size: formatPx(30);
              line-height: formatPx(40);
            }
          }
        }
      }

      .bargain-situation-bargaining {
        margin-top: formatPx(20);
        height: formatPx(200);
      }

      .bargain-situation-record {
        margin-top: formatPx(20);
        height: calc(100% - #{formatPx(700)});
        overflow: auto;
      }
    }
  }

</style>
